import fs from 'fs'
import fetch from 'node-fetch'
import puppeteer from '../../lib/puppeteer/puppeteer.js'
import MysInfo from '../genshin/model/mys/mysInfo.js'
const link = 'https://ghfast.top/https://github.com/devil233-ui/Tloml-Starry/resources/raw/master/resources/json/mihoyo/'

export class GenshinWorldBossKillCountInventory extends plugin {
    constructor() {
        super({
            name: 'genshin-world-boss-kill-count-inventory',
            dsc: '原神世界BOSS击杀数量查询',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^#(原神)?(世界)?BOSS击杀$/i, fnc: 'getBossKillCount' },
                { reg: /^#(原神)?(世界)?BOSS击杀排行$/i, fnc: 'getBossKillRanking' }
            ]
        })
    }

    async checkAndCreateHtmlFile(filePath, fetchUrl) {
        if (!fs.existsSync(filePath)) {
            fs.mkdirSync('resources/html', { recursive: true })
            const htmlContent = await (await fetch(fetchUrl)).text()
            fs.writeFileSync(filePath, htmlContent)
        }
    }

    async getBossKillCount() {
        await this.checkAndCreateHtmlFile('resources/html/原神BOSS击杀数.html', link.replace('json/mihoyo/', 'html/原神BOSS击杀数.html'))

        const userUid = await MysInfo.getUid(this.e)
        if (!userUid) return false

        let response = await MysInfo.get(this.e, 'index')
        const excludedBossNames = new Set(await (await fetch(`${link}excludedNames.json`)).json())
        const bossOrder = await (await fetch(`${link}order.json`)).json()

        let inventoryData = await Promise.all(response.data.world_explorations
            .filter(({ name }) => !excludedBossNames.has(name))
            .map(async ({ name, boss_list }) => {
                const bossIconData = await (await fetch(`${link}bossIcon.json`)).json()
                return {
                    name,
                    boss_list: boss_list.map(boss => ({
                        ...boss,
                        icon: `https://${bossIconData[boss.name]}.png?x-oss-process=image/quality,q_75/resize,s_120`
                    }))
                }
            })
        )
        inventoryData.sort((a, b) => bossOrder.indexOf(a.name) - bossOrder.indexOf(b.name))

        const inventoryImage = await puppeteer.screenshot('原神BOSS击杀数', {
            tplFile: 'resources/html/原神BOSS击杀数.html',
            data: inventoryData
        })

        if (!fs.existsSync('data/GenshinWorldBossKillNumberData.json')) {
            fs.writeFileSync('data/GenshinWorldBossKillNumberData.json', JSON.stringify({}, null, 4))
        }

        const GenshinWorldBossKillNumberData = JSON.parse(fs.readFileSync('data/GenshinWorldBossKillNumberData.json', 'utf8'))
        GenshinWorldBossKillNumberData[userUid] = inventoryData.flatMap(boss =>
            boss.boss_list.map(bossItem => ({
                name: bossItem.name,
                icon: bossItem.icon,
                kill_num: bossItem.kill_num
            }))
        );
        fs.writeFileSync('data/GenshinWorldBossKillNumberData.json', JSON.stringify(GenshinWorldBossKillNumberData, null, 4))

        return this.reply(inventoryImage)
    }

    async getBossKillRanking() {
        await this.checkAndCreateHtmlFile('resources/html/原神BOSS击杀排行.html', link.replace('json/mihoyo/', 'html/原神BOSS击杀排行.html'))

        const data = JSON.parse(fs.readFileSync('data/GenshinWorldBossKillNumberData.json', 'utf8'))
        const ranking = new Map()

        for (const uid in data) {
            data[uid].forEach(boss => {
                const existingBoss = ranking.get(boss.name)
                if (!existingBoss || boss.kill_num > existingBoss.count) {
                    ranking.set(boss.name, { count: boss.kill_num, uid, icon: boss.icon }) // 更新最高击杀记录
                }
            })
        }

        const rankingArray = Array.from(ranking.entries()).map(([name, { count, uid, icon }]) => ({
            name,
            count,
            uid,
            icon
        }))

        const inventoryImage = await puppeteer.screenshot('原神BOSS击杀排行', {
            tplFile: 'resources/html/原神BOSS击杀排行.html',
            data: rankingArray
        })

        return this.reply(inventoryImage)
    }
}